class Admin::CategoriesController < ApplicationController
	
	def index
		@categories = Category.find_all_by_parent_id(nil)
			.sort_by { |c| c.order_position }
			.paginate(page: params[:page])
	end
	
	def show
		@category = Category.find(params[:id])
	end
	
	def new
		@category = Category.new()
		@traceability_action = :created_by
	end
	
	def create
		params[:category] = params[:category].merge(created_by: self.class.name)
		# Replace id by object
		params[:category][:parent] = Category.find(params[:category][:parent])
		
		@category = Category.create(params[:category])
		if @category.errors.any?
            @errors = @category.errors
			render 'new'
		else
			redirect_to [:admin, @category], flash: { success: t('admin.category.create.success') }
		end
	end
	
	def edit
		@category = Category.find(params[:id])
		@traceability_action = :updated_by
	end
	
	def update
		@category = Category.find(params[:id])
		
		# Replace id by object
		params[:category][:parent] = Category.find(params[:category][:parent])
		
		if @category.update_attributes(params[:category])
			redirect_to [:admin, @category], flash: { success: t('admin.category.update.success') }
		else
            @errors = @category.errors
			render 'edit'
		end
	end
	
	def destroy
		Category.find(params[:id]).destroy
		redirect_to categories_path, flash: { success: t('admin.category.delete.success') }
	end
	
end
